package com.qyhl.webtv.module_circle.circle.usercenter;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.circle.CircleUCenterBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.circle.msg.chat.ChatMessageActivity;
import com.qyhl.webtv.module_circle.utils.itemview.ItemCircleUserPicture;
import com.qyhl.webtv.module_circle.utils.itemview.ItemCircleUserTxt;
import com.qyhl.webtv.module_circle.utils.itemview.ItemCircleUserVideo;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.leancloud.chatkit.utils.LCIMConstants;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/1/24.
 * 圈子个人首页
 */

@Route(path = ARouterPathConstant.CIRCLE_USER ,extras = ARouterPathConstant.LOGIN_NEEDED)
public class CircleUserActivity extends BaseActivity implements CircleUserContract.CircleUserView {
    @BindView(R2.id.head_icon)
    ImageView headIcon;
    @BindView(R2.id.head_layout)
    RelativeLayout headLayout;
    @BindView(R2.id.follow_num)
    TextView followNum;
    @BindView(R2.id.tag_follow)
    TextView tagFollow;
    @BindView(R2.id.fans_num)
    TextView fansNum;
    @BindView(R2.id.nickName)
    TextView nickName;
    @BindView(R2.id.collapsing_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R2.id.app_bar)
    AppBarLayout appBar;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.toolbar)
    Toolbar mUsertoolbar;
    @BindView(R2.id.tochat)
    TextView tochat;
    @BindView(R2.id.follow_btn)
    TextView followBtn;
    @BindView(R2.id.bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R2.id.title)
    TextView title;

    private boolean followEnable = true;
    private boolean shieldEnable = true;
    private CircleUCenterBean mBean;
    private CircleUserPresenter mPresenter;

    @Autowired(name = "dstusername")
    String dstUsername;

    private MultiItemTypeAdapter mAdapter;

    private List<CircleHomeBean> mDataList;

    private EmptyWrapper emptyWrapper;

    private String lastId = "0";

    private CollapsingToolbarLayoutState state;
    private String userName;

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    private Menu mMenu;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0xff393e3f);
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.circle_activity_circle_ucenter;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        userName = CommonUtils.getInstance().getUserName();
        mPresenter = new CircleUserPresenter(this);
        initView();
        mPresenter.getCenterInfo(userName, dstUsername, lastId);
    }

    @Override
    protected void setListener() {
        setListeners();
    }

    /**
     * 初始化
     */
    private void initView() {
        mDataList = new ArrayList<>();
        loadMask.setStatus(LoadingLayout.Loading);
        mAdapter = new MultiItemTypeAdapter(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemCircleUserPicture(this, mDataList));
        mAdapter.addItemViewDelegate(new ItemCircleUserVideo(this, mDataList));
        mAdapter.addItemViewDelegate(new ItemCircleUserTxt(this, mDataList));

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);
        refresh.setNestedScrollingEnabled(true);

        title.setText("");
        setSupportActionBar(mUsertoolbar);
        toolbarLayout.setFocusable(false);
        toolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        emptyWrapper = new EmptyWrapper(mAdapter);

        emptyWrapper.setEmptyView(R.layout.circle_layout_circle_content_emptyview);
        recyclerView.setAdapter(emptyWrapper);

        if (dstUsername.equals(userName)) {
            bottomLayout.setVisibility(View.GONE);
        } else {
            bottomLayout.setVisibility(View.VISIBLE);
//            mUsertoolbar.inflateMenu(R.menu.circle_user_menu);
        }

    }

    /**
     * 监听
     */
    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = "0";
                mPresenter.getCenterInfo(userName, dstUsername, lastId);
            }
        });
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lastId = "0";
                mPresenter.getCenterInfo(userName, dstUsername, lastId);
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getMoreInfo(userName, dstUsername, lastId);
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mDataList.get(position).getId() + "");
                RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        //关注监听
        followBtn.setOnClickListener(v -> {
            if (followEnable) {
                followEnable = false;
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            //判断如果是关注状态
                            if ("已关注".equals(followBtn.getText().toString())) {
                                mPresenter.undoFollow(dstUsername);
                            } else {
                                mPresenter.doFollow(dstUsername);
                            }
                        } else {
                            RouterManager.routerLogin(CircleUserActivity.this, 0);
                            Toasty.normal(CircleUserActivity.this, "尚未登录或登录已失效").show();
                            followEnable = true;
                        }
                    }

                    @Override
                    public void error(String s) {
                        followEnable = true;
                    }
                });

            }
        });

        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                        title.setText("");
                        toolbarLayout.setExpandedTitleTextColor(getResources().getColorStateList(R.color.white));
                        mUsertoolbar.setNavigationIcon(R.drawable.small_video_back_btn);
                        mUsertoolbar.setOverflowIcon(ContextCompat.getDrawable(CircleUserActivity.this, R.drawable.icon_user_more));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            Window window = getWindow();
                            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                            window.setStatusBarColor(0xff393e3f);
                            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        }
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        title.setText(mBean.getUser().getNickName());//设置title为EXPANDED
                        toolbarLayout.setCollapsedTitleTextColor(getResources().getColorStateList(R.color.global_black_lv1));
                        mUsertoolbar.setNavigationIcon(R.drawable.btn_back_default);
                        mUsertoolbar.setOverflowIcon(ContextCompat.getDrawable(CircleUserActivity.this, R.drawable.icon_user_more_pre));
                        state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            Window window = getWindow();
                            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                            window.setStatusBarColor(0xffffffff);
                            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                        }
                    }
                } else {
                    if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                        toolbarLayout.setTitle("");
                        state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                    }
                }
            }
        });

        tochat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            mPresenter.checkShield(dstUsername);
                        } else {
                            Toasty.normal(CircleUserActivity.this, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(CircleUserActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            }
        });
    }

    /**
     * 获取信息成功
     *
     * @param bean
     */
    @Override
    public void getSuccess(CircleUCenterBean bean) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setStatus(LoadingLayout.Success);
        mBean = bean;

        //昵称
        nickName.setText(bean.getUser().getNickName());

        if (bean.isFollow()) {
            followBtn.setText("已关注");
            followBtn.setTextColor(getResources().getColor(R.color.cirlce_black));
            followBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.circle_user_follow_on), null, null, null);
        } else {
            followBtn.setText("关注");
            followBtn.setTextColor(getResources().getColor(R.color.global_base));
            followBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.circle_user_follow_off), null, null, null);
        }

        //头像
        Glide.with(this)
                .load(mBean.getUser().getLogo())
                .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).transform(new GlideCircleTransform(this)))
                .into(headIcon);

        followNum.setText(mBean.getFollowCount() + "");
        fansNum.setText(mBean.getFansCount() + "");

        try {
            lastId = bean.getTopicList().get(bean.getTopicList().size() - 1).getId() + "";
        } catch (Exception e) {
            lastId = "0";
        }
        if (!dstUsername.equals(userName)) {
            if (mBean.isShield()) {
                mMenu.findItem(R.id.shield).setTitle("取消屏蔽");
            } else {
                mMenu.findItem(R.id.shield).setTitle("屏蔽");
            }
        }


        mDataList.clear();
        mDataList.addAll(bean.getTopicList());

        emptyWrapper.notifyDataSetChanged();

    }

    /**
     * 设置更多内容
     *
     * @param beanList
     */
    @Override
    public void setMoreInfo(List<CircleHomeBean> beanList) {
        refresh.finishLoadMore();
        lastId = beanList.get(beanList.size() - 1).getId() + "";

        mDataList.addAll(beanList);

        emptyWrapper.notifyDataSetChanged();
    }

    @Override
    public void getError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
    }

    @Override
    public void getNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setNoNetworkText(msg);
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        Toasty.normal(this, msg).show();
    }

    @Override
    public void showLog(String msg) {
        refresh.finishLoadMore();
        Log.i("info", msg);
    }

    @Override
    public void followSuccess(String msg) {
        Toasty.normal(this, msg).show();
        followBtn.setText("已关注");
        followBtn.setTextColor(getResources().getColor(R.color.cirlce_black));
        followBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.circle_user_follow_on), null, null, null);
        followEnable = true;
    }

    @Override
    public void followError(String msg) {
        Toasty.normal(this, msg).show();
        followEnable = true;
    }

    @SuppressLint("NewApi")
    @Override
    public void unFollowSuccess(String msg) {
        Toasty.normal(this, msg).show();
        followBtn.setText("关注");
        followBtn.setTextColor(ContextCompat.getColor(CircleUserActivity.this, R.color.global_base));
        followBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.circle_user_follow_off), null, null, null);
        followEnable = true;
    }

    @Override
    public void unFollowError(String msg) {
        Toasty.normal(this, msg).show();
        followEnable = true;
    }

    /**
     * 屏蔽成功
     *
     * @param msg
     */
    @Override
    public void blockSuccess(String msg) {
        Toasty.normal(this, msg).show();
        mMenu.findItem(R.id.shield).setTitle("解除屏蔽");
        shieldEnable = true;
    }

    /**
     * 屏蔽失败
     *
     * @param msg
     */
    @Override
    public void blockError(String msg) {
        Toasty.normal(this, msg).show();
        shieldEnable = true;
    }

    /**
     * 解除屏蔽
     *
     * @param msg
     */
    @Override
    public void unBlockSuceess(String msg) {
        Toasty.normal(this, msg).show();
        mMenu.findItem(R.id.shield).setTitle("屏蔽");
        shieldEnable = true;
    }

    /**
     * 解除屏蔽失败
     *
     * @param msg
     */
    @Override
    public void unBlockError(String msg) {
        Toasty.normal(this, msg).show();
        shieldEnable = true;
    }

    @Override
    public void checkPass() {
        Intent intent = new Intent(CircleUserActivity.this, ChatMessageActivity.class);
        intent.putExtra(LCIMConstants.PEER_ID, mBean.getUser().getUsername());
        startActivity(intent);
    }

    @Override
    public void checkUnPass(String msg) {
        Toasty.normal(this, msg).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("圈子个人主页");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.CIRCLEUSER);
    }

    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("圈子个人主页");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.CIRCLEUSER);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!dstUsername.equals(userName)) {
            getMenuInflater().inflate(R.menu.circle_user_menu, menu);
            mMenu = menu;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        int i = item.getItemId();//屏蔽
        if (i == R.id.shield) {
            if (shieldEnable) {
                shieldEnable = false;
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if ("屏蔽".equals(item.getTitle().toString())) {
                                mPresenter.doBlock(dstUsername);
                            } else {
                                mPresenter.undoBlock(dstUsername);
                            }
                        } else {
                            Toasty.normal(CircleUserActivity.this, "尚未登录或登录已失效").show();
                            RouterManager.routerLogin(CircleUserActivity.this, 0);
                            shieldEnable = true;
                        }
                    }

                    @Override
                    public void error(String s) {
                        shieldEnable = true;
                    }
                });

            }

            //举报
        } else if (i == R.id.complain) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        Bundle bundle = new Bundle();
                        bundle.putString("type", "10");
                        bundle.putString("username", mBean.getUser().getUsername());
                        RouterManager.router(ARouterPathConstant.CIRCLE_COMPLAIN,bundle);

                    } else {
                        Toasty.normal(CircleUserActivity.this, "尚未登录或登录已失效").show();
                        RouterManager.routerLogin(CircleUserActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (i == android.R.id.home) {
            finish();

        } else {
        }
        return super.onOptionsItemSelected(item);
    }
}
